package com.tencent.miniproject.presenter;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.util.Log;

import com.tencent.miniproject.been.ImageLabelBeen;
import com.tencent.miniproject.been.PublishBeen;
import com.tencent.miniproject.constants.Constant;
import com.tencent.miniproject.presenter.i.IPublishInfoPresenter;
import com.tencent.miniproject.ui.i.IPublishInfoActivity;
import com.tencent.miniproject.utils.GsonUtil;
import com.tencent.miniproject.utils.OkHttpResultCallback;
import com.tencent.miniproject.utils.OkHttpUtil;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PublishInfoPresenter implements IPublishInfoPresenter {

    //绑定activity
    private IPublishInfoActivity mView;
    //请求拍照的requestcode
    public static final int TAKE_PHOTO = 1000;

    public PublishInfoPresenter(IPublishInfoActivity activity) {
        super();
        this.mView = activity;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void takePhoto(Context context, Uri imageUri) {
        Uri photoUri = FileProvider.getUriForFile(context,
                context.getApplicationContext().getPackageName()
                        + ".com.tencent.miniproject.provider", Objects.requireNonNull(createImageFile(context)));


//        try {
//
//            if (createSuccess){
//                imageUri = Uri.fromFile(output);
//                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                mView.startActivityFromPresenter(intent, TAKE_PHOTO);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 文件转base64字符串
     *
     * @param file
     * @return
     */
    public String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            int length = in.read(bytes);
            base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return base64;
    }

    /**
     * 获取图片类别
     *
     * @param picFile picFile
     */
    @Override
    public void getPicTagFromNet(File picFile) {
//        MediaType type = MediaType.parse("multipart/form-data");//"text/xml;charset=utf-8"
//        RequestBody fileBody = RequestBody.create(type, picFile);
//        Request request = new Request.Builder().url("http://111.230.93.13:18080")
//                .addHeader("User-Agent", "android")
//                .header("Content-Type", "multipart/form-data")
//                .post(fileBody)//传参数、文件或者混合，改一下就行请求体就行
//                .build();
//        OkHttpClient client = new OkHttpClient();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.i("xxx", "onFailure: " + call.toString());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//                Log.i("xxx","1、连接的消息"+response.message());
//                if(response.isSuccessful()){
//                    Log.i("xxx","2、连接成功获取的内容"+response.body().string());
//                }
//            }
//        });


        List<File> files = new ArrayList<>();
        files.add(picFile);

//        String fileStr = fileToBase64(picFile);
//        Log.i("ning", "getPicTagFromNet: " + fileStr);
//        Map<String, String> map = new HashMap<>();
//        map.put("file", fileStr);
        OkHttpUtil.getInstance().postAsync(Constant.SERVER_URL + "/post/getImgLabel", new OkHttpResultCallback() {
            @Override
            public void onError(Call call, Exception e) {
                Log.i("shaidan", "onError: " + call.toString());
                mView.setPublishButtonCanClick(true);
            }

            @Override
            public void onResponse(byte[] bytes) {
                mView.setPublishButtonCanClick(true);
                String string = new String(bytes);
                string = unicodeToString(string).replaceAll("u'", "'").replaceAll("\\\\", "").replaceAll("'", "\"").replace("\"[","[").replace("]\"", "]");
                ImageLabelBeen labelBeen = GsonUtil.gsonToBean(string, ImageLabelBeen.class);

                Log.i("ning", "onResponse: " + string);
                if (labelBeen.getMessage() == null || labelBeen.getMessage().size() == 0){
                    return;
                }
                mView.showTagFromNet(labelBeen.getMessage().get(0).getTag_name());
            }
        }, null, files);
    }

    public static String unicodeToString(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch+"" );
        }
        return str;
    }



    /**
     * unicode 转换成 utf-8
     * @author fanhui
     * 2007-3-15
     * @param theString
     * @return
     */
    public String unicodeToUtf8(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len;) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    /**
     * 发送数据
     *
     * @param publishBeen been
     */
    @Override
    public void publishData(Context context, PublishBeen publishBeen, File picFile) {
        List<File> files = new ArrayList<>();
        files.add(picFile);
        Log.i("ning", "publishData: " + picFile.length());
        OkHttpUtil.getInstance().postAsync(Constant.SERVER_URL + "/post/releasePost", new OkHttpResultCallback() {
            @Override
            public void onError(Call call, Exception e) {
                Log.i("ning", "onError: " + call.toString());
                mView.showPublishResult(false);
            }

            @Override
            public void onResponse(byte[] bytes) {
                String string = new String(bytes);
                Log.i("ning", "onResponse: " + string);
                if (string.contains("success")){
                    mView.showPublishResult(true);
                }else {
                    mView.showPublishResult(false);
                }
            }
        }, transBeenToMap(publishBeen), files);
    }

    /**
     * 实体类转Map
     *
     * @param publishBeen been
     * @return map
     */
    private Map<String, String> transBeenToMap(PublishBeen publishBeen) {
        if (publishBeen == null) {
            return new HashMap<>();
        }
        Map<String, String> parmas = new HashMap<>();
        parmas.put("content", publishBeen.getContent());
        parmas.put("position", publishBeen.getPosition());
        parmas.put("longitude", String.valueOf(publishBeen.getLongitude()));
        parmas.put("latitude", String.valueOf(publishBeen.getLatitude()));
        parmas.put("store", publishBeen.getStore());
        parmas.put("imgLabel", publishBeen.getImgLabel());
        parmas.put("releaseTime", String.valueOf(publishBeen.getReleaseTime()));
        parmas.put("cost", publishBeen.getCost());
        parmas.put("district", publishBeen.getDistrict());
        return parmas;
    }

    /**
     * 根据需要传给后台的参数生成实例对象
     *
     * @param content     content
     * @param position    position
     * @param longitude   longitude
     * @param latitude    latitude
     * @param store       store
     * @param imgLabel    imgLabel
     * @param releaseTime releaseTime
     * @param cost        cost
     * @return been
     */
    @Override
    public PublishBeen getPublishBeen(String content, String position, Double longitude,
                                      Double latitude, String store, String imgLabel,
                                      Date releaseTime, String cost, String district) {
        PublishBeen publishBeen = new PublishBeen();
        publishBeen.setContent(content);
        publishBeen.setPosition(position);
        publishBeen.setLongitude(longitude);
        publishBeen.setLatitude(latitude);
        publishBeen.setStore(store);
        publishBeen.setImgLabel(imgLabel);
        publishBeen.setReleaseTime(releaseTime);
        publishBeen.setCost(cost);
        publishBeen.setDistrict(district);
        return publishBeen;
    }

    /**
     * 判断是否可以发布，必须保证参数不能为空
     *
     * @param picFile   图片
     * @param location  位置
     * @param longitude 经度
     * @param latitude  纬度
     * @param imgLabel  标签
     * @param cost      消费
     * @return false
     */
    @Override
    public boolean canPublishData(File picFile, String location, Double longitude, Double latitude,
                                  String imgLabel, String cost) {
        if (picFile == null || "".equals(location) || longitude == null || latitude == null ||
                "".equals(imgLabel) || "".equals(cost)) {
            return false;
        }
        return true;
    }

    private File createImageFile(Context context) {
        File output = new File(context.getCacheDir(), "publish_photo");
        if (output.exists()) {
            output.delete();
        }
        try {
            boolean createSuccess = output.createNewFile();
            if (createSuccess) {
                return output;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
